package com.zhongzhi.springboot.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.springframework.stereotype.Component;

import com.zhongzhi.springboot.pojo.Equipment;
/**
 * 此对象为plc数据获取类
 * @author Administrator
 *
 */
@Component()
public class PlcUtil {

	//获取plc连接套接字对象
	public Socket getSocket(Equipment e) throws IOException {
		Integer port = e.getPort();
		String host = e.getHost();
		if(host!=null && port !=null) {
			Socket socket = new Socket(host,port);
			return socket;
		}else {
			return null;
		}
	}
	
	//发送数据返回字符串
		private  String getString(Socket socket,String s) throws IOException {
			InputStream inputStream = socket.getInputStream();
			OutputStream outputStream = socket.getOutputStream();
			outputStream.write(s.getBytes());
			outputStream.flush();
			int len = inputStream.read();
			char[] inputchar = new char[len];
			for (int i = 0; i < len; i++) {
				inputchar[i] = (char)(byte)inputStream.read();
			}
			return String.copyValueOf(inputchar);
		}
		
		
	//获取plc数据
	//发送geth命令,获取高度数据
	//高度格式	123.0,222.2,56.7
	//用","分割字符串,第一个就是通道1数据,第二个就是通道2数据
	
	public String getHeight(Socket socket) throws IOException {
		return getString(socket, "geth");
	}
	
	//将获取的数据信息分解,获取通道数据
	public Double getData(String s,Integer num) {
		String[] ss = s.split(",");
		if(num>ss.length) {
			return null;
		}
		try {
			Double d = Double.valueOf(ss[num-1]);
			return d;
		} catch (Exception e) {
			return null;
		}
	}
	
	//获取plc连接状态
	//发送测试字符test.返回ok字符
	public Boolean getConnect(Socket socket){
		String str;
		try {
			str = getString(socket, "test");
			if (str.equals("ok")) {
				return true;
			}else {
				return false;
			}
		} catch (IOException e) {
			return false;
		}
		
	}
	
	
	
	
}
